package org.binglan.youziyuepai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.binglan.youziyuepai.entity.PersonalDynamicApply;
import org.binglan.youziyuepai.enums.code.StatusEnum;
import org.binglan.youziyuepai.exception.MyException;
import org.binglan.youziyuepai.mapper.PersonalDynamicApplyMapper;
import org.binglan.youziyuepai.service.PersonalDynamicApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 约拍申请表 服务实现类
 * </p>
 *
 * @author sanjin
 * @since 2019-04-24
 */
@Service
public class PersonalDynamicApplyServiceImpl extends ServiceImpl<PersonalDynamicApplyMapper, PersonalDynamicApply> implements PersonalDynamicApplyService {


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PersonalDynamicApply savePersonalDynamicApply(PersonalDynamicApply personalDynamicApply) {
        int insert = this.baseMapper.insert(personalDynamicApply);
        personalDynamicApply.setId(insert);
        return personalDynamicApply;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<PersonalDynamicApply> queryReceivePersonalDynamicApplyByUserId(String userId) {
        return this.baseMapper.queryReceivePersonalDynamicApplyByUserId(userId);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<PersonalDynamicApply> querySendPersonalDynamicApplyByUserId(String userId) {

        PersonalDynamicApply apply = new PersonalDynamicApply();
        apply.setApplyUserId(userId);
        return this.list(new QueryWrapper<>(apply));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public PersonalDynamicApply changeDatePatApplyStatus(String userId, Integer applyId, StatusEnum statusEnum) {
        PersonalDynamicApply apply = this.getById(applyId);
        if (apply == null) {
            throw new MyException("applyId 不正确");
        }
        if (!apply.getStatus().equals(StatusEnum.IGNORE.getCode())) {
            throw new MyException("您已经拒绝或接受该条约拍申请，不能再进行更改");
        }
        if (apply.getStatus().equals(statusEnum.getCode())) {
            throw new MyException("约拍申请的状态已经是 "+apply.getStatus());
        }
        apply.setStatus(statusEnum.getCode());
        this.updateById(apply);
        return apply;
    }
}
